import React, { useCallback, useImperativeHandle, useMemo, useRef } from 'react';
import { useEffect, useState } from 'react';
import './index.less';
import { useModel } from 'umi';
import DataGrid, { Column } from 'devextreme-react/data-grid';

import Popup from 'devextreme-react/popup';
import Button from 'devextreme-react/button';
import { getPaperList } from '../service';
import { CallingCpasexe, fjAndDgDataCode, intl, rTime, waitTime, resDataFilter } from '@/utils';
import notify from 'devextreme/ui/notify';
import type { AuditPaperItem } from '../data';
import SaveTemplate from "./components/SaveTemplate"
// import RenNameDialog from '../InputDialog/renNameDialog';
import { Dropdown, Popover, Typography } from 'antd';
import type { MenuProps } from 'antd';
import {
  deletePaper,
  restorePaper,
  clearRecycle,
  PaperRenname,
  getPhaseTreeBatchReplace,
  getTplList,
} from './service';
import ErrorBounced from '@/pages/components/ErrorBounced/index';
import { openFile } from '@/utils/electronUtil';
import RelationDrawer from './components/RelationDrawer';
import PaperInitializes from './components/PaperInitializes';
import DgSignature from './components/DgSignature';
import { CpasIcon } from '~/public/cpas-ui';
import { getCpasIcon } from '@/utils/icon';
import ExportTemplate from './components/ExportTemplate';
import DevDefaultPopup from '~/public/cpas-ui/components-ui/express-components/DevPopup/DevPopup';
import { LoadIndicator } from 'devextreme-react';


const { io } = require('socket.io-client')
const { Text } = Typography;

const XMType = window.sessionStorage.electronParams
  ? JSON.parse(window.sessionStorage.electronParams)?.params?.XMType
  : "单机审计项目";

const PaperTable: React.FC<any> = React.forwardRef((props: any, ref) => {
  const { initialState } = useModel('@@initialState');
  const { zcbfid, dbname, sjxmbh } = initialState?.curPart as API.CurPart;
  const { username, usercode, aesPassword } = initialState?.curUser as API.CurUser;
  const password = window.main.cryptoUtil(aesPassword);
  const { curPhase, onMenuItemClieck } = props; // 当前选中的阶段
  const [openVisible111111, setOpenVisible111111] = useState<boolean>(false);
  // const [focusedRowKey11, setFocusedRowKey11] = useState<any>('');



  const [deletePopupProps, setDeletePopupProps] = useState<{
    visible?: boolean;
    onConfirm?: () => void;
    onCancel?: () => void;
    title?: string;
    content?: string;
  }>({
    visible: false,
    onConfirm: async () => { },
    onCancel: async () => { },
    title: '',
    content: '',
  });

  const [tableData, setTableData] = useState<any[]>([]);
  const tplDialogRef = useRef<any>();
  const relationRef = useRef<any>(); // 关系抽屉
  const DevSortableGridRef = useRef<any>(); // 关系抽屉
  const InitializesRef = useRef<any>();
  const SignatureRef = useRef<any>();// 批量签名
  const SaveTemplateRef = useRef<any>();
  const selRowDataRef = useRef<any>();
  const ExportTemplateRef = useRef<any>();
  const InputDialogRef = useRef<any>();
  const modalExtensions = ["doc", "docx", "xls", "xlsx", "jpg", "gif", "bmp", "png", "txt", "pdf", "rar", "rar4", "zip", "mp3", "mp4",
    'xlsm', 'xltm', 'xlam', 'xlsb', 'csv'];

  const fetchData = async () => {
    // console.log(curPhase, '@@@  树节点node');
    let sjjd: string | undefined = curPhase?.lx == 2 ? curPhase.id : '';
    if (curPhase?.id === 'recycleBin') {
      sjjd = 'recycleBin';
    }
    setOpenVisible111111(true);

    const res = await getPaperList({
      dbname,
      zcbfid,
      dgnd: curPhase?.lx > 0 ? curPhase.dgnd : '',
      sjjd: sjjd,
    });
    if (res.success) {
      setTableData(res.data);
    } else {
      setTableData([]);
    }
    await waitTime(500);
    setOpenVisible111111(false);
  };

  useEffect(() => {
    if (dbname && curPhase?.id) {

      fetchData();
    }
  }, [dbname, curPhase]);

  useEffect(() => {
    if (!curPhase?.id) return;
    const socket = io('http://localhost:8070');
    socket.on('connect', () => {
      const engine = socket.io.engine;
      console.log('socket connect: ', engine.transport.name); // in most cases, prints "polling"
    });
    socket.on('refreshUI', async (msg: any) => {
      console.log('on refresh ui event: ', msg);
      if (msg === 'workpaper') {
        await fetchData();
      } else {
        notify('同步失败！', 'error', 2000);
      }
    });
    return () => {
      socket.close();
    }
  }, [curPhase])

  // 自定义方法
  useImperativeHandle(ref, () => ({
    refresh: () => {
      if (curPhase?.id) {
        fetchData();
      } else {
        setTableData([]);
      }

    },
  }));

  /** 
   * 打开底稿
   * item 文件名，如 2017_货币资金.xlsx
   */
  const openDg = useCallback((item: AuditPaperItem) => {
    if (item?.dgnd) {
      openFile([sjxmbh, zcbfid, '底稿', item.dgnd + '_' + item.dgmc + item.dglx].join('/'));
    }
  }, []);


  const dataMenuRegExp = (dataValue: any) => {
    let regName = /\.(jpg|gif|png|jpeg|webp|txt|xlsx|xlsd|pdf|doc|docx|ppt|pptx|rm|avi|mov|mpg|mp4|wav|mp3|aif)$/;
    if (regName.test(dataValue)) {
      return true;
    } else {
      notify('文件后缀必须是.jpg,.gif,.png,.jpeg,.webp,.txt,.xlsx,.xlsd,.pdf,.doc,.docx,.ppt,.pptx,.rm,.avi,.mov,.mpg,.mp4,.wav,.mp3,.aif,请重新修改', 'warning', 2000)
      return false;
    }
  }


  // 单个删除、批量删除 事件
  const fun_BatchDelete = async (rowDataTemp: any, itmeObj: any) => {

    let contentText = '';
    if (itmeObj?.tempDgnd) {
      contentText = `确定要删除【${itmeObj.tempDgnd}-${[itmeObj.tempDgmc]}】吗？`
    } else {
      contentText = `共选择 ${rowDataTemp.length} 个,确定要删除吗？`
    }

    setDeletePopupProps({
      visible: true,
      title: intl('audit.paper.del', '删除'),
      content: contentText,
      onConfirm: async () => {
        setDeletePopupProps({
          visible: false
        });
        // 设置删除弹窗
        const res = await deletePaper(rowDataTemp, dbname, sjxmbh, zcbfid, usercode, username);
        if (res.success) {
          const resFilter = resDataFilter(res.data);
          if (resFilter.success) {
            const { reDataArr } = resFilter;
            if (reDataArr.tempError.length) {
              return tplDialogRef.current.show({
                args: {
                  codes: true,
                  data: reDataArr.tempError,
                },
              });
            }
            await fetchData();
            notify('删除成功！', 'success', 3000);
            DevSortableGridRef?.current?.instance?.clearSelection();
          } else {
            notify('删除失败', 'error', 2000);
          }
        } else {
          notify('删除失败', 'error', 2000);
        };
      },
      onCancel: () => {
        setDeletePopupProps({
          visible: false,
        });
      },
    });
  }



  // 选中当前行
  const tableSelectRowID = async (tempDgID: string = '') => {
    let selID = '';
    if (tempDgID) {
      selID = tempDgID;
    } else {
      selID = selRowDataRef.current.dgid;
    }
    await DevSortableGridRef.current?.instance.selectRows(selID);
  }
  function dataMenuItems(e: any) {
    if (!e.row) return;
    console.log(e, 'e-------------------');
    tableSelectRowID(e.row.key);
    // 数据上的菜单
    if (e.target == 'content' && e.row?.rowType == 'data') {
      const rowData: AuditPaperItem & any = e.row?.data;
      console.log(rowData, 'data-------------------');
      const Parperid = rowData.dgnd + rowData.dgmc;
      e.items = [
        {
          icon: 'iconfont icon-dakai',
          text: intl('paper.open', '打开'),
          onItemClick: () => openDg(rowData),
        },
        {
          icon: 'iconfont icon-zhongmingming',
          text: intl('audit.paper.rename', '重命名'),
          onItemClick: () => {
            if (!InputDialogRef.current) return;
            InputDialogRef.current.show({
              title: "底稿重命名",
              value: rowData.dgmc + rowData.dglx,
              // regExpFunc: (v: any) => { return dataMenuRegExp(v) },
              okCallback: async (value: any) => {
                // 使用 test 方法检查文件名是否匹配正则表达式
                const extensionRegex = /\.[a-zA-Z0-9]+$/;
                let textVal = '';
                if (extensionRegex.test(value)) {
                  textVal = value;
                } else {
                  textVal = value + rowData.dglx;
                }
                const r = await PaperRenname(dbname, zcbfid, sjxmbh, Parperid, textVal, rowData.dgsyh);

                if (r.success) {
                  const resFilter = resDataFilter(r.data);
                  if (resFilter.success) {
                    const { reDataArr } = resFilter;
                    if (reDataArr.tempError.length) {
                      const resNew = fjAndDgDataCode(reDataArr.tempError[0].code);
                      return notify(`${resNew}!`, 'error', 3000);
                    }
                    notify("重命名成功", "success", 2000);
                    fetchData();
                  } else {
                    notify('重命名失败', 'error', 2000);
                  }
                } else {
                  notify('重命名失败', 'error', 2000);
                };

              },
              onCancel: () => { }
            });
          },
        },
        {
          icon: 'iconfont icon-delete',
          text: intl('audit.paper.del', '删除'),
          visible: rowData.dgzt <= 1 || rowData.dgzt === null,
          onItemClick: async () => {
            fun_BatchDelete([rowData], { tempDgnd: rowData.dgnd, tempDgmc: rowData.dgmc });
          },
        },
        {
          icon: 'iconfont icon-yidongdao',
          text: intl('audit.paper.move', '移动到'),
          onItemClick: () => {
            onMenuItemClieck({ from: 'dg', itemID: 'moveToPhase', data: rowData });
          },
        },
        {
          icon: 'iconfont icon-tihuan',
          beginGroup: true,
          text: intl('paper.replace', '替换'),
          items: [
            {
              text: intl('paper.replaceFromTemplate', '从模板替换'),
              onItemClick: () => {
                onMenuItemClieck({ from: 'dg', itemID: 'replaceFromTemplate', data: rowData });
              },
            },
            {
              text: intl('paper.replaceFromFile', '从外部文件替换'),
              visible: rowData.dgzt <= 1 || rowData.dgzt === null,
              onItemClick: async () => {
                const dgData = await window.electronComponents.openDialog({
                  properties: ['openFile'],
                  filters: [
                    {
                      name: 'Office Files',
                      extensions: modalExtensions,
                    },
                    {
                      name: 'all',
                      extensions: ['*'],
                    },
                  ],
                });
                const dgDataPath = dgData.filePaths;
                if (!dgData.canceled) {
                  const r: any = await getPhaseTreeBatchReplace(
                    username,
                    [rowData.dgid],
                    sjxmbh,
                    zcbfid,
                    dgDataPath.toString(),
                    dbname,
                  );
                  if (r.success) {
                    const resFilter = resDataFilter(r.data);
                    if (resFilter.success) {
                      const { reDataArr } = resFilter;
                      if (reDataArr.tempError.length) {
                        const resNew = fjAndDgDataCode(reDataArr.tempError[0].code);
                        return notify(`${resNew}!`, 'error', 3000);
                      }
                      notify("替换文件成功", "success", 2000);
                      fetchData();
                    } else {
                      notify('替换文件失败', 'error', 2000);
                    }
                  } else {
                    notify('替换文件失败', 'error', 2000);
                  };
                }
              },
            },
            {
              text: intl('paper.replaceFromFolder', '从文件夹批量替换'),
              onItemClick: async () => {
                onMenuItemClieck({ from: 'dg', itemID: 'replaceFromFolder', data: rowData });

              },
            },
          ],
        },
        {
          icon: 'iconfont icon-fujian',
          text: intl('paper.attach', '附件'),
          onItemClick: async () => {
            relationRef.current.show(rowData, 'attach');
          },
        },
        {
          icon: 'iconfont icon-shuxing',
          beginGroup: true,
          text: intl('paper.props', '属性'),
          onItemClick: async () => {
            relationRef.current.show(rowData, 'props');
          },
        },
      ];
    }
  }

  const fun_ClearRecycle = async (singleSelect: any[], titleText: string) => {
    setDeletePopupProps({
      visible: false,
    });
    const res = await clearRecycle(singleSelect, dbname, sjxmbh, zcbfid);
    if (res.success) {
      const resFilter = resDataFilter(res.data);
      if (resFilter.success) {
        const { reDataArr } = resFilter;
        if (reDataArr.tempError.length) {
          return tplDialogRef.current.show({
            args: {
              codes: true,
              data: reDataArr.tempError,
            },
            okCallback: (tempData: any[]) => {
              console.log(tempData, '@@@ okCallback');

            }
          });
        }
        await fetchData();
        notify(`${titleText}成功！`, 'success', 3000);
      } else {
        notify(`${titleText}失败！`, 'errors', 3000)
      }
    } else {
      notify(`${titleText}失败！`, 'errors', 3000)
    }
  }

  function recycleBinMenu(e: any) {
    if (!e.row) return;
    tableSelectRowID(e.row.key);
    // 回收站右键菜单
    if (e.target == 'content' && e.row?.rowType == 'data') {
      // const singleSelect = DevSortableGridRef.current.instance.getSelectedRowsData();
      const rowData: AuditPaperItem & any = e.row?.data;
      console.log(rowData, '@@@ rowData');
      e.items = [
        {
          icon: 'share',
          text: intl('paper.restore', '还原'),
          onItemClick: () => {
            if (!rowData?.dgid) return notify('请选择要还原文件！', 'error', 3000);
            setDeletePopupProps({
              visible: true,
              title: intl('paper.restore', '还原'),
              content: intl('audit.recycleBin.delContent', '确定要还原吗？文件将回到原目录。'),
              onConfirm: async () => {
                const res = await restorePaper([rowData], dbname, zcbfid, sjxmbh, usercode, username);
                if (res.success) {
                  await fetchData();
                  setDeletePopupProps({
                    visible: false,
                  });
                }
              },
              onCancel: () => {
                setDeletePopupProps({
                  visible: false,
                });
              },
            });
          },
        },
        {
          icon: 'iconfont icon-delete',
          text: intl('audit.recycleBin.del', '彻底删除'),
          onItemClick: () => {
            if (!rowData?.dgid) return notify('请选择要彻底删除文件！', 'error', 3000);
            setDeletePopupProps({
              visible: true,
              title: intl('audit.recycleBin.del', '彻底删除'),
              content: intl('audit.recycleBin.delContent', '确定要彻底删除吗？此操作不可逆！'),
              onConfirm: () => {
                fun_ClearRecycle([rowData], '彻底删除');
              },
              onCancel: () => {
                setDeletePopupProps({
                  visible: false,
                });
              },
            });
          },
        },
      ];
    }
  }


  const dropdownItems: MenuProps['items'] = [
    {
      key: '0',
      label: '打开',
      className: "DropdownMenuStyle",
      icon: <CpasIcon type='icon-dakai' fontSize={18} />,
      onClick: async () => {
        await tableSelectRowID();
        openDg(selRowDataRef.current);
      }
    },
    {
      key: '1',
      label: '重命名',
      className: "DropdownMenuStyle",
      icon: <CpasIcon type='icon-zhongmingming' fontSize={18} />,
      onClick: async () => {
        await tableSelectRowID();
        if (!InputDialogRef.current) return;
        const Parperid = selRowDataRef.current.dgnd + selRowDataRef.current.dgmc;
        InputDialogRef.current.show({
          title: "底稿重命名",
          value: selRowDataRef.current.dgmc + selRowDataRef.current.dglx,
          // regExpFunc: (v: any) => { return dataMenuRegExp(v) },
          okCallback: async (value: any) => {
            // 使用 test 方法检查文件名是否匹配正则表达式
            const extensionRegex = /\.[a-zA-Z0-9]+$/;
            let textVal = '';
            if (extensionRegex.test(value)) {
              textVal = value;
            } else {
              textVal = value + selRowDataRef.current.dglx;
            }
            const r = await PaperRenname(dbname, zcbfid, sjxmbh, Parperid, textVal, selRowDataRef.current.dgsyh)
            if (r.success) {
              fetchData();
              notify('重命名成功', 'success', 3000)
            } else {
              notify('重命名失败', 'error', 3000);
            }

          },
          onCancel: () => { }
        });
      }
    },
    {
      key: '2',
      className: "DropdownMenuStyle",
      icon: <CpasIcon type='icon-yidongdao' fontSize={18} />,
      label: intl('audit.paper.move', '移动到'),
      onClick: async () => {
        await tableSelectRowID();
        const rowData = selRowDataRef.current;
        onMenuItemClieck({ from: 'dg', itemID: 'moveToPhase', data: rowData });
      },
    },
    {
      key: '3',
      className: "DropdownMenuStyle",
      icon: <CpasIcon type='icon-tihuan' fontSize={18} />,
      label: intl('paper.replace', '替换'),
      children: [
        {
          key: '3-1',
          className: "DropdownMenuStyle",
          label: intl('paper.replaceFromTemplate', '从模板替换'),
          onClick: () => {
            tableSelectRowID();
            const rowData = selRowDataRef.current;
            onMenuItemClieck({ from: 'dg', itemID: 'replaceFromTemplate', data: rowData });
          },
        },
        {
          key: '3-2',
          className: "DropdownMenuStyle",
          label: intl('paper.replaceFromFile', '从外部文件替换'),
          onClick: async () => {
            await tableSelectRowID();
            const rowData = selRowDataRef.current;
            if (rowData.dgzt > 1 || rowData.dgzt <= -1) return notify('禁止删除', 'error', 2000);
            const dgData = await window.electronComponents.openDialog({
              properties: ['openFile'],
              filters: [
                {
                  name: 'Office Files',
                  extensions: modalExtensions,
                }, { name: 'all', extensions: ["*"] }
              ],
            });
            const dgDataPath = dgData.filePaths;
            if (!dgData.canceled) {
              const res = await getPhaseTreeBatchReplace(
                username,
                [rowData.dgid],
                sjxmbh,
                zcbfid,
                dgDataPath.toString(),
                dbname,
              )
              if (res.success) {
                notify('替换成功', 'success', 3000)
                await fetchData();
              } else {
                if (res.data?.length) {
                  tplDialogRef.current.show({
                    args: {
                      codes: true,
                      data: res.data,
                    },
                    okCallback: (tempData: any[]) => {
                      console.log(tempData, '@@@ okCallback');

                    }
                  });
                } else {
                  notify('替换失败', 'error', 3000)
                }
              }
            }
          },
        }, {
          key: '3-3',
          // className: "DropdownMenuStyle",//不要这个,限制了宽度,会换行
          label: intl('paper.replaceFromFolder', '从文件夹批量替换'),
          onClick: async () => {
            await tableSelectRowID();
            const rowData = selRowDataRef.current;
            onMenuItemClieck({ from: 'dg', itemID: 'replaceFromFolder', data: rowData });

          },
        },
      ],
    },
    {
      key: 'shuxing',
      label: '属性',
      className: "DropdownMenuStyle",
      icon: <CpasIcon type='icon-shuxing' fontSize={18} />,
      onClick: async () => {
        await tableSelectRowID();
        relationRef.current.show(selRowDataRef.current, 'props');
      },
    },
  ]

  const cellRenderCilk = (cell: any) => {
    if (curPhase?.id === 'recycleBin') {
      return <div style={{ display: "flex", alignItems: 'center', justifyContent: 'center', }}>
        <div className="Icon_Style" >
          <CpasIcon type='icon-delete' onClick={async () => {
            await tableSelectRowID(cell.data.dgid)
            setDeletePopupProps({
              visible: true,
              title: intl('audit.recycleBin.del', '彻底删除'),
              content: intl('audit.recycleBin.delContent', '确定要彻底删除吗？此操作不可逆！'),
              onConfirm: async () => {
                setDeletePopupProps({
                  visible: false,
                });
                // 因为后端参数只能接受array，所以这里分类讨论
                const rowData = cell.data;
                fun_ClearRecycle([rowData], '彻底删除');
              },
              onCancel: () => {
                setDeletePopupProps({
                  visible: false,
                });
              },
            });
          }} />
        </div>
      </div>
    } else {
      return <div style={{ display: "flex", alignItems: 'center', justifyContent: 'center', }}>
        <div className="Icon_Style">
          <CpasIcon type='icon-fujian' onClick={async () => {
            const rowData = cell.data;
            await tableSelectRowID(rowData.dgid);
            relationRef.current.show(rowData, 'attach');
          }} />
        </div>
        <div className="Icon_Style">
          <CpasIcon type='icon-delete' onClick={async () => {
            const rowData = cell.data;
            if (rowData.dgzt > 1 || rowData.dgzt <= -1) return notify('禁止删除', 'error', 2000);
            await tableSelectRowID(rowData.dgid);
            fun_BatchDelete([rowData], { tempDgnd: rowData.dgnd, tempDgmc: rowData.dgmc });
          }} />
        </div>
        <div className="Icon_Style">
          <Dropdown menu={{ items: dropdownItems }}
            // trigger={['click']}
            onOpenChange={() => {
              selRowDataRef.current = cell.data;
            }}
          >
            <i className='iconfont icon-ellipsis' />
          </Dropdown>
        </div>

      </div>
    }
  }
  // 移动底稿
  function dgRemoving(e: any) {
    e.cancel = false;
    notify(e.data.dgid + ' removed');
  }

  // const onFocusedRowChanged = useCallback((e: any) => {
  //   // const data = e.row.data;
  //   // const progress = data.Task_Completion ? `${data.Task_Completion}%` : '';
  //   // setTaskSubject(data.Task_Subject);
  //   // setTaskDetails(data.Task_Description);
  //   // setTaskStatus(data.Task_Status);
  //   // setTaskProgress(progress);
  //   console.log(e, e.component.option('focusedRowKey'), '@@@ ');
  //   // const scrollableSet = DevSortableGridRef?.current?.instance?.getScrollable();
  //   // scrollableSet?.scrollTo({ top: 0 });
  //   if (e.component.option('focusedRowKey')) {
  //     setFocusedRowKey11(e.component.option('focusedRowKey'));

  //   }
  // }, []);

  const Grid = useMemo(() => {
    return (
      <>
        <DataGrid
          className='PaperDevSortableGrid devHeadersCenter'
          key={`${new Date().getTime()}`}
          onInitialized={(e: any) => {
            e.component.pageIndex(0); // 重置页面索引为0
          }}
          ref={DevSortableGridRef}
          dataSource={tableData}
          id='dgid'
          keyExpr="dgid"
          height="100%"
          width="100%"
          cellHintEnabled={true}
          hoverStateEnabled={true}
          showBorders={true}
          showColumnLines={true}
          allowColumnReordering={true}
          // 显示行的线
          showRowLines={true}
          allowColumnResizing={true}
          columnChooser={{ enabled: true }}
          columnFixing={{ enabled: true }}
          headerFilter={{ visible: true }}
          paging={{ enabled: false }}
          onRowRemoving={dgRemoving}
          searchPanel={{
            visible: true,
            width: 230,
            placeholder: ''
          }}
          selection={{
            mode: 'multiple',
            selectAllMode: 'allPages',
            showCheckBoxesMode: 'onClick',
            // deferred: true
          }}
          scrolling={{
            mode: "virtual",
            rowRenderingMode: "virtual",
            renderAsync: true
          }}
          onContextMenuPreparing={curPhase?.id === 'recycleBin' ? recycleBinMenu : dataMenuItems}
          toolbar={{
            items: [
              {
                // cssClass: 'attachmentButton',
                location: 'after',
                widget: 'dxButton',
                visible: XMType === '单机审计项目' ? false : true,
                options: {
                  text: '同步',
                  type: "default",
                  height: "31px",
                  onClick: () => {
                    CallingCpasexe({
                      usercode,
                      password,
                      zcbfid,
                      BusType: 0,
                    })
                  },
                }
              },
              {
                location: 'before',
                text: curPhase?.text || '',
              },
              {
                name: 'searchPanel',
              },
              {
                location: 'after',
                widget: 'dxButton',
                cssClass: 'refreshButton_Style',
                options: {
                  icon: "iconfont icon-refresh",
                  onClick: async () => {
                    fetchData();
                  },
                },
              },
              {
                cssClass: 'PaperMenuItems',
                locateInMenu: 'always',
                widget: 'dxButton',
                options: {
                  icon: 'iconfont icon-digaochushihua',
                  text: intl('paper.initPaper', '底稿初始化'),
                  onClick: async () => {
                    const res = await getTplList();
                    if (res.success) {
                      InitializesRef.current.show({
                        args: {
                          title: '底稿初始化',
                          codes: true,
                          data: res.data
                        },
                        okCallback: () => {
                          // 确定的回调函数
                          props?.paperPhaseTreeReload(true);
                          fetchData();
                        }
                      });
                    }

                  },

                },
              },
              {
                cssClass: 'PaperMenuItems',
                locateInMenu: 'always',
                widget: 'dxButton',
                options: {
                  text: intl('paper.saveAsTpl', '保存为底稿模板'),
                  icon: 'iconfont icon-baocunweidigaomoban',
                  onClick: () => {
                    SaveTemplateRef.current.show()
                  }
                },
              },
              // 7-17之后-------------
              {
                cssClass: 'PaperMenuItems',
                locateInMenu: 'always',
                widget: 'dxButton',
                options: {
                  text: intl('paper.exportPaper', '导出底稿'),
                  icon: 'iconfont icon-daochudigao',
                  onClick: async () => {
                    ExportTemplateRef.current.show();
                  }
                }
              },
              {
                cssClass: 'PaperMenuItems',
                locateInMenu: 'always',
                visible: curPhase?.text === '回收站',
                widget: 'dxButton',
                options: {
                  text: intl('paper.deleteAll', '批量还原'),
                  icon: 'iconfont icon-piliangyidong',
                  onClick: async () => {
                    const selData = DevSortableGridRef.current.instance.getSelectedRowsData();
                    if (selData.length === 0) {
                      notify("未选中底稿，请至少选中一个", "warning", 2000)
                    } else {
                      console.log(selData, '@@@批量还原');
                      const res = await restorePaper(selData, dbname, zcbfid, sjxmbh, usercode, username);
                      if (res) {
                        setDeletePopupProps({
                          visible: false,
                          onConfirm: async () => { },
                          onCancel: async () => { },
                          title: '',
                          content: '',
                        });
                        await fetchData();
                      }
                    }
                  },
                },
              },
              {
                cssClass: 'PaperMenuItems',
                locateInMenu: 'always',
                widget: 'dxButton',
                visible: curPhase?.text !== '回收站',
                options: {
                  text: intl('paper.deleteAll', '批量移动'),
                  icon: 'iconfont icon-piliangyidong',
                  onClick: async () => {
                    const data = DevSortableGridRef.current.instance.getSelectedRowsData();
                    if (data.length === 0) {
                      notify("未选中底稿，请至少选中一个", "warning", 2000)
                    } else {
                      onMenuItemClieck({ from: 'dg', itemID: 'moveToPhase', data });
                    }
                  },
                },
              },

              {
                cssClass: 'PaperMenuItems',
                locateInMenu: 'always',
                widget: 'dxButton',
                visible: curPhase?.text !== '回收站',
                options: {
                  text: "批量删除",
                  icon: 'iconfont icon-piliangshanchu',
                  onClick: () => {
                    const selectedData = DevSortableGridRef.current.instance.getSelectedRowsData();
                    if (selectedData.length > 0) {
                      fun_BatchDelete(selectedData, {});
                    } else {
                      notify("未选中底稿，请至少选中一个", "warning", 2000)
                    }
                  }
                },
              },
              {
                cssClass: 'PaperMenuItems',
                locateInMenu: 'always',
                widget: 'dxButton',
                visible: curPhase?.text === '回收站',
                options: {
                  text: "清空回收站",
                  icon: 'info',
                  onClick: async () => {
                    await DevSortableGridRef.current.instance.selectAll();
                    const allData = await DevSortableGridRef.current.instance.getSelectedRowsData();
                    if (allData?.length === 0) return notify("未选中底稿，请至少选中一个", "warning", 2000);
                    console.log(allData, '@@@ 清空回收站');
                    setDeletePopupProps({
                      visible: true,
                      title: intl('paper.recycleBin.empty', '清空回收站'),
                      content: intl(
                        'audit.recycleBin.emptyAll',
                        '确定要清空回收站吗？此操作不可逆并将彻底删除回收站所有文件！',
                      ),
                      onConfirm: () => {
                        fun_ClearRecycle(allData, '清空回收站');
                      },
                      onCancel: () => {
                        setDeletePopupProps({
                          visible: false,
                        });
                      },
                    });
                  }
                },
              },
              {
                cssClass: 'PaperMenuItems',
                name: 'columnChooserButton',
                locateInMenu: 'always',
              },
            ],
          }}
          onCellDblClick={(r: any) => {
            if (r.rowType !== "header") openDg(r.data);
          }}

          columnResizingMode="widget"
          columnMinWidth={80}
          // 显示斑马线
          rowAlternationEnabled={true}
        >
          <Column
            allowResizing={true}
            allowHeaderFiltering={false}
            caption={intl('paper.col.index', '索引号')}
            dataField="dgsyh" alignment='left' width={80} />
          <Column
            allowHeaderFiltering={false}
            allowResizing={true}
            alignment='left'
            caption={intl('paper.col.dgmc', '底稿名称')}
            dataField="dgmc"
            cellRender={(cell) => {
              return (
                <>
                  <span style={{ marginRight: '5px' }}> {getCpasIcon(cell.data.dglx)}</span>
                  <Text style={{ width: 'calc(100% - 25px)' }} ellipsis={{ tooltip: `${cell.data.dgmc}${cell.data.dglx}` }}>
                    {curPhase?.text === '回收站' && `${cell.data.dgnd}_`}{cell.data.dgmc + cell.data.dglx}
                  </Text>
                </>
              );

            }}
          />
          <Column
            caption={intl('paper.col.fjCnt', '附件')}
            dataField="fjCnt"
            alignment='right'
            allowHeaderFiltering={false}
            cellRender={(cell: any) => {
              return <div>
                <Popover content={() => (<div>查看附件</div>)} placement="bottom">
                  <span onClick={() => {
                    relationRef.current.show(cell.data, 'attach');
                  }}>
                    {cell.data?.fjCnt > 0 ? cell.data.fjCnt : ''}
                  </span>
                </Popover>
              </div>;
            }}
            width={80}

          />
          <Column
            allowHeaderFiltering={false}
            alignment='center'
            caption={intl('paper.col.editUser', '编辑人')}
            dataField="editUser"
            // allowResizing={true}
            width={220}
            cellRender={(cell) => {
              return <>
                <Text style={{ marginRight: '5px', width: 'calc(100% - 10px)' }} ellipsis={{ tooltip: `${cell.data.editUser} ${cell.data.editDate ? rTime(cell.data.editDate) : ''}` }}>
                  {cell.data.editUser} &nbsp;&nbsp; {cell.data.editDate ? rTime(cell.data.editDate) : ''}
                </Text>
              </>
            }}
            fixed={true}
            fixedPosition='right'
          />
          <Column
            allowHeaderFiltering={false}
            allowResizing={false}
            alignment='center'
            caption={intl('paper.col.editUser', '操作')}
            width={130}
            cellRender={(cell) => cellRenderCilk(cell)}
            fixed={true}
            fixedPosition='right'
          />
        </DataGrid >
      </>)
  }, [tableData]);

  const loadIndicatorTemp = useMemo(() => {
    return (<> {openVisible111111 && <div style={{
      position: 'absolute', top: "0px", left: "0px", width: '100%', height: '100%', display: 'flex', alignItems: "center", justifyContent: "center", borderRadius: '5px',
      opacity: 0.5, zIndex: "9", background: "#ddd"
    }}>
      <LoadIndicator id="medium-indicator" height={50} width={50} />
    </div>} </>)
  }, [openVisible111111]);

  async function DrawerResh(value: boolean) {
    if (value) await fetchData();
  };
  return (
    <>
      <div style={{ width: '100%', height: '100%', position: 'relative' }}>
        {loadIndicatorTemp}
        {Grid}
      </div>

      <ConfirmPopup
        visible={deletePopupProps?.visible}
        // 点击确定 事件
        onConfirm={deletePopupProps?.onConfirm}
        // 点击取消 事件
        onCancel={deletePopupProps?.onCancel}
        title={deletePopupProps?.title}
        content={deletePopupProps?.content}
      />
      <ErrorBounced ref={tplDialogRef} />

      <RelationDrawer ref={relationRef} DrawerResh={DrawerResh} />
      <PaperInitializes ref={InitializesRef} />
      <DgSignature ref={SignatureRef} />
      <SaveTemplate ref={SaveTemplateRef} curPhaseData={curPhase?.dgnd} />
      <ExportTemplate ref={ExportTemplateRef} />

      <DevDefaultPopup.Input ref={InputDialogRef} />


    </>
  );
});

const ConfirmPopup = (props: {
  visible?: boolean;
  onConfirm?: () => void;
  onCancel?: () => void;
  title?: string;
  content?: string;
}) => {
  return (
    <Popup
      visible={props?.visible}
      title={props?.title}
      onHiding={props?.onCancel}
      width={400}
      height={200}
      showTitle={true}
      showCloseButton={true}
      closeOnOutsideClick={true}
      contentRender={() => {
        return (
          <div>
            <div>{props?.content}</div>
            <div
              style={{
                display: 'flex',
                position: 'absolute',
                bottom: '10px',
                right: '20px',
              }}
            >
              <Button
                width={88}
                text={intl('paper.cancel', '取消')} onClick={props?.onCancel} />
              <Button
                width={88}
                type='default'
                style={{ marginRight: '10px' }}
                text={intl('paper.confirm', '确定')}
                onClick={props?.onConfirm}
              />

            </div>
          </div>
        );
      }}
    />
  );
};

export default PaperTable;
